﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.IsolatedStorage;
using RSSReader.MobileClient.Model;
using System.Net;
using System.Xml.Linq;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Text.RegularExpressions;

namespace RSSReader.MobileClient.ViewModel
{
    class ArticleViewModel
    {
        public ObservableCollection<Article> Articles { get; set; }
        public ObservableCollection<string> ArticlesUrl { get; set; }
        public AsyncDataManager AsyncDM { get; set; }
        public AsyncDataManager AsyncDM2 { get; set; }
        public WCFWebRoleService.DataDistributorClient GetFavRead = new WCFWebRoleService.DataDistributorClient();

        public ArticleViewModel()
        {
            Articles = new ObservableCollection<Article>();
            ArticlesUrl = new ObservableCollection<string>();
        }

        public void GetArticles(String CUri, AsyncDataManager b)
        {
            AsyncDM = b;
            GetDefaultArticles(CUri);
        }

        public void GetAllArticles(IDictionary<string, string> Querykeys, AsyncDataManager b)
        {
            AsyncDM = b;
            foreach (var item in Querykeys)
            {
                if (item.Key != "LocLink")
                {
                    prepareConn(item.Value);
                }
            }
        }

        public void GetDefaultArticles(String CUri)
        {
            ObservableCollection<Article> a = new ObservableCollection<Article>();
            prepareConn(CUri);
            Articles = a;
        }

        public void GetSavedArticles()
        {

        }


        private void prepareConn(String CUri)
        {
            WebClient wc = new WebClient();
            wc.Encoding = System.Text.Encoding.UTF8;
            wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
            try
            {
                wc.DownloadStringAsync(new Uri(CUri), CUri);
            }
            catch
            {
                return;
            }
        }

        private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
                return;
            try
            {
                XElement xmlitems = XElement.Parse(e.Result);
                List<XElement> elements = xmlitems.Descendants("item").ToList();
                List<XElement> temp = xmlitems.Descendants("channel").ToList();
                string originfeed = temp[0].Element("title").Value;
                var Luri = (string)e.UserState;
                ObservableCollection<Article> aux = new ObservableCollection<Article>();
                foreach (XElement rssItem in elements)
                {
                    Article rss = new Article();
                    rss.FeedOrigin = originfeed.Replace("&#160;", " ");
                    rss.Body = rssItem.Element("description").Value.Replace("&#160;", " ");
                    rss.Body = rss.Body.Replace("&#8230;", ".");
                    rss.UrlLink = rssItem.Element("link").Value.Replace("&#160;", " ");
                    ArticlesUrl.Add(rssItem.Element("link").Value.Replace("&#160;", " "));
                    rss.Title = rssItem.Element("title").Value;
                    rss.FeedOriginUrl = Luri;
                    rss.isFavImg = "/Images/favs.addto.png";
                    rss.Link = String.Format("/ArticleDisplayPage.xaml?title={0}&body={1}&link={2}&source={3}&sourceurl={4}", rssItem.Element("title").Value.Replace("&#160;", " "), rss.Body, rssItem.Element("link").Value.Replace("&#160;", " "), rss.FeedOrigin.Replace("&#160;", " "), rss.FeedOriginUrl);
                    rss.Favit = String.Format("/ActionPage.xaml?FavArticle=False&title={0}&body={1}&link={2}&source={3}&sourceurl={4}", rssItem.Element("title").Value.Replace("&#160;", " "), rss.Body, rssItem.Element("link").Value.Replace("&#160;", " "), rss.FeedOrigin.Replace("&#160;", " "), rss.FeedOriginUrl);
                    rss.isReadBrush = new SolidColorBrush(Color.FromArgb(0, 0, 0, 255));
                    rss.isFavBrush = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255));
                    //START OF THE IMG DL --- IF THE FEED CONTAINS AN IMAGE IT IS STORED FOR LATER
                    string ImgSource = Regex.Match(rssItem.Element("description").Value, "<img.+?src=[\"'](.+?)[\"'].*?>", RegexOptions.IgnoreCase).Groups[1].Value;
                    if (ImgSource != "")
                    {
                        WebClient imageGetter = new WebClient();
                        imageGetter.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_ImageDLCompleted);
                        imageGetter.DownloadStringAsync(new Uri(ImgSource));
                    }
                    //END OF THE IMG DL
                    //START CHECK IF THE ARTICLE IS READ
                    //END OF CHECK IF ARTICLE IS READ
                    //aux.Add(rss);
                    Articles.Add(rss);
                }
                //Articles = aux;
                AsyncDM.ManageCallbacks("Data2");
                AsyncDM.ManageCallbacks("ImagesDL");
            }
            catch
            {
                AsyncDM.ManageCallbacks("Data2");
                AsyncDM.ManageCallbacks("ImagesDL");
                return;
            }
        }

        public void GetFavArticles(AsyncDataManager a)
        {
            AsyncDM2 = a;

            try
            {
                GetFavRead.GetUserArticlesCompleted += new EventHandler<WCFWebRoleService.GetUserArticlesCompletedEventArgs>(CallBackUserArticles);
                GetFavRead.GetUserArticlesAsync(ArticlesUrl, App.UserId);
            }
            catch
            {
                AsyncDM.ManageCallbacks("GotRead");
                AsyncDM.ManageCallbacks("GotFav");
            }

        }

        private void CallBackUserArticles(object sender, WCFWebRoleService.GetUserArticlesCompletedEventArgs e)
        {
            foreach (var key in e.Result.Keys)
            {
                foreach (var User in e.Result[key])
                {
                    var Arti = Articles.Where(w => w.UrlLink == User.Url).FirstOrDefault();
                    if (Arti != null)
                    {
                        if (Arti.UrlLink == User.Url)
                        {
                            Arti.isRead = true;
                            Arti.isReadBrush = new SolidColorBrush(Color.FromArgb(77, 77, 77, 255));
                            Arti.isFav = User.IsFavorite;
                            if (Arti.isFav == true)
                            {
                                Arti.isFavBrush = new SolidColorBrush(Color.FromArgb(255, 255, 251, 0));
                                Arti.Favit = Arti.Favit.Replace("FavArticle=False", "FavArticle=True");
                            }
                            Arti.isFavImg = "/Images/favs.png";
                        }
                    }
                    /*foreach (var Arti in Articles)
                    {
                        if (Arti.Link == User.Url)
                        {
                            Arti.isRead = true;
                            Arti.isFav = User.IsFavorite;
                        }
                    }*/
                }
            }
            AsyncDM2.ManageCallbacks("GotRead");
            AsyncDM2.ManageCallbacks("GotFav");
        }

        public void GetReadArticles()
        {
             
        }

        public void ArticleIsRead(string url, string desc, string titl, string source)
        {
            Dictionary<WCFWebRoleService.UserSubscriptionInformation,ObservableCollection<WCFWebRoleService.UserArticleInformation>> Info = new Dictionary<WCFWebRoleService.UserSubscriptionInformation,ObservableCollection<WCFWebRoleService.UserArticleInformation>>();
            WCFWebRoleService.UserSubscriptionInformation Usub = new WCFWebRoleService.UserSubscriptionInformation();
            ObservableCollection<WCFWebRoleService.UserArticleInformation> Uart = new ObservableCollection<WCFWebRoleService.UserArticleInformation>();

            Usub.Url = source;
            
            Uart.Add(new WCFWebRoleService.UserArticleInformation { Url = url, PublicationDate= null, Description = desc, Title = titl });
            Info.Add(Usub, Uart);
            try
            {
                GetFavRead.UpdateUserArticlesAsync(Info, App.UserId);
            }
            catch
            {

            }

        }

        public void FavArticle(string desc, string titl, string url, string source, bool iFa)
        {
            Dictionary<WCFWebRoleService.UserSubscriptionInformation, ObservableCollection<WCFWebRoleService.UserArticleInformation>> Info = new Dictionary<WCFWebRoleService.UserSubscriptionInformation, ObservableCollection<WCFWebRoleService.UserArticleInformation>>();
            WCFWebRoleService.UserSubscriptionInformation Usub = new WCFWebRoleService.UserSubscriptionInformation();
            ObservableCollection<WCFWebRoleService.UserArticleInformation> Uart = new ObservableCollection<WCFWebRoleService.UserArticleInformation>();

            Usub.Url = source;

            Uart.Add(new WCFWebRoleService.UserArticleInformation { Url = url, PublicationDate = null, Description = desc, Title = titl, IsFavorite = iFa });
            Info.Add(Usub, Uart);
            try
            {
                GetFavRead.UpdateUserArticlesAsync(Info, App.UserId);
            }
            catch
            {

            }

        }

        private void wc_ImageDLCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            AsyncDM.ManageCallbacks("ImagesDL");
        }
    }
}

